package main

//type ListNode struct {
//	Val  int
//	Next *ListNode
//}

func mergeKLists(lists []*ListNode) *ListNode {
	if len(lists) == 0 {
		return nil
	}
	f := 0
	for i := 0; i < len(lists); i++ {
		if lists[i] != nil {
			f++
			break
		}
	}
	if f == 0 {
		return nil
	}

	lists1 := lists
	dummy := &ListNode{}
	current := dummy
	//current = current.Next
	v := lists1[0]
	k := 0
	b := 0

	for !nil1(lists1) {
		a := 0
		for d, list := range lists1 {
			b = d
			if list == nil {
				a++
				continue
			}
			if list.Val <= v.Val {
				v = list
				k = d
			}
		}
		if a == len(lists1)-1 {
			current.Next = lists1[b]
			break

		}
		current.Next = v
		current = current.Next
		//current.Next = nil
		lists1[k] = lists1[k].Next
		if current.Next != nil {
			v = current.Next
		} else {
			v = current
		}

	}
	return dummy.Next

}
func nil1(lists []*ListNode) bool {
	for _, list := range lists {
		if list != nil {
			return false
		}
	}
	return true
}

//func printList2(head *ListNode) {
//	for head != nil {
//		fmt.Print(head.Val, " ")
//		head = head.Next
//	}
//	fmt.Println()
//}

func main() {
	// 示例 1
	//l1 := &ListNode{Val: 1, Next: &ListNode{Val: 4, Next: &ListNode{Val: 5}}}
	//l2 := &ListNode{Val: 1, Next: &ListNode{Val: 3, Next: &ListNode{Val: 4}}}
	//l3 := &ListNode{Val: 2, Next: &ListNode{Val: 6}}
	//lists := []*ListNode{l1, l2, l3}
	//
	//abc := mergeKLists(lists) // 输出: 1 1 2 3 4 4
	//printList2(abc)

	l1 := &ListNode{}
	l2 := &ListNode{Val: 1}
	lists := []*ListNode{l1, l2}

	abc := mergeKLists(lists) // 输出: 1 1 2 3 4 4
	printList2(abc)           // 输出: 空
}
